import time
import threading

from model.db.name_mapping import refresh_name_cache
from utils.utils import etcd_client, NAME_MAPPING_WATCH_KEY


def put_etcd_watch_key():
    ts = str(time.time())
    etcd_client.put(NAME_MAPPING_WATCH_KEY, ts)
    print(f"[etcd] Updated {NAME_MAPPING_WATCH_KEY} with timestamp {ts}")


def etcd_watch_callback(event, app):
    """
    etcd key 变更时触发的回调函数（手动进入 Flask 应用上下文 app context）
    """
    with app.app_context():
        print(f"[etcd] etcd key update triggered, refreshing cache...")
        refresh_name_cache()


def start_etcd_watch_thread(app):
    """
    启动监听线程，监听 /name_mapping/update
    """

    def _watch():
        print(f"[etcd] Watching key: {NAME_MAPPING_WATCH_KEY}")
        try:
            etcd_client.add_watch_callback(
                NAME_MAPPING_WATCH_KEY,
                lambda event: etcd_watch_callback(event, app)
            )
        except Exception as e:
            print(f"[etcd] Watch error: {e}")

    # 开启后台线程监听 etcd
    thread = threading.Thread(target=_watch, daemon=True)
    # Notice 设置为守护线程 跟随flask项目主线程共同停止
    thread.daemon = True
    thread.start()
